package com.example.defaultshop;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.AsyncTask.Status;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.ProgressBar;

public class PreviousOrderActivity extends Activity implements OnTaskCompleted {
	private ArrayList<Item> items;

	private SwipeRefreshLayout swipe;
	private ProgressBar progress;
	private ListView list;
	private Activity context;
	private Button back, add;

	private SharedPreferences preferences;
	private OnTaskCompleted callback;
	private ShopApplication app;
	private CopyTask cTask;
	private ItemTask iTask;
	
	private boolean[] checked;
	
	private int basketId;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_previous);
		
		context = (Activity) this;
		app = (ShopApplication) getApplicationContext();
		preferences = getSharedPreferences("DefaultShop", MODE_PRIVATE);
		
		basketId = getIntent().getIntExtra("basketId", -1);

		callback = (OnTaskCompleted) this;
		
		progress = (ProgressBar) findViewById(R.id.progressBar1);
		
        swipe = (SwipeRefreshLayout) findViewById(R.id.swipe);
		swipe.setProgressViewOffset(false, 0, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, getResources().getDisplayMetrics()));
        swipe.setOnRefreshListener(new OnRefreshListener() {
			@Override
			public void onRefresh() {
				iTask = new ItemTask();
				iTask.execute();
			}
		});
		
		list = (ListView) findViewById(android.R.id.list);
		list.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				if (items.get(position).getIdx() > 0) {
					checked[position] = !checked[position];
					CheckBox check = (CheckBox) view.findViewById(R.id.chkItem);
					check.setChecked(checked[position]);
				}
			}
		});
		
		back = (Button) findViewById(R.id.btnPreviousBack);
		back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		add = (Button) findViewById(R.id.btnPrevieousAdd);
		add.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				AlertDialog.Builder builder = new AlertDialog.Builder(context);
	    		builder.setMessage(R.string.dialog_copy_order)
	    		       .setTitle(R.string.obs)
	    		       .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								String ids = "";
								for (int i = 0; i < checked.length; i++) {
									if (checked[i] && items.get(i).getIdx() > 0)
										ids += (ids.length() == 0 ? "" : ",") + items.get(i).getIdx();
								}
								progress.setVisibility(View.VISIBLE);
								add.setVisibility(View.INVISIBLE);
								cTask = new CopyTask();
								cTask.execute(Server.getCopyOrderXml(app.getBasketId(), basketId, app.getShop().getIdx(), true, preferences.getString("phone", ""), ids));
							}
						})
						.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								String ids = "";
								for (int i = 0; i < checked.length; i++) {
									if (checked[i] && items.get(i).getIdx() > 0)
										ids += (ids.length() == 0 ? "" : ",") + items.get(i).getIdx();
								}
								progress.setVisibility(View.VISIBLE);
								add.setVisibility(View.INVISIBLE);
								cTask = new CopyTask();
								cTask.execute(Server.getCopyOrderXml(app.getBasketId(), basketId, app.getShop().getIdx(), false, preferences.getString("phone", ""), ids));
							}
						});
	    		AlertDialog dialog = builder.create();
	    		dialog.show();
			}
		});

		swipe.setRefreshing(true);
		iTask = new ItemTask();
		iTask.execute();
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		
		if (iTask != null)
			if (iTask.getStatus() == Status.RUNNING)
				iTask.cancel(true);
		
		if (cTask != null)
			if (cTask.getStatus() == Status.RUNNING)
				cTask.cancel(true);
		
		app.stopTasks();
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		
		Calendar date = Calendar.getInstance();
		Calendar deadline = app.getShop().getDeadline();
		if (date.get(Calendar.YEAR) != deadline.get(Calendar.YEAR) || date.get(Calendar.MONTH) != deadline.get(Calendar.MONTH) || date.get(Calendar.DAY_OF_MONTH) != deadline.get(Calendar.DAY_OF_MONTH)) {
			Intent intent = new Intent(this, CampaignActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
		}
	}

	@Override
	public void onTaskCompleted(boolean success) {
		if (success)
			list.invalidateViews();
	}
	
	private class CopyTask extends AsyncTask<String, Void, Boolean> {
		@Override
		protected Boolean doInBackground(String... params) {
			try {
				InputStream in = Server.post(Server.COPY, params[0]);
				XmlPullParser parser = Server.toXmlParser(in);
				int basketId = XmlParser.getBasketId(parser);
				return basketId != -1;
			} catch (IOException e) {
				Log.e("Shop", "IOException: " + e.getMessage());
				return false;
			} catch (XmlPullParserException e) {
				Log.e("Shop", "XmlPullParserException: " + e.getMessage());
				return false;
			} catch (NullPointerException e) {
    			Log.e("Shop", "NullPointerException: " + e.getMessage());
				return false;
			} catch (IllegalArgumentException e) {
    			Log.e("Shop", "IllegalArgumentException: " + e.getMessage());
    			return false;
    		}
		}
		
		@Override
	    protected void onPostExecute(Boolean success) {
			if (success) {
				Intent intent = new Intent(context, BasketActivity.class);
				intent.putExtra("copied", true);
				startActivity(intent);
				finish();
			} else {
				AlertDialog.Builder builder = new AlertDialog.Builder(context);
	    		builder.setMessage(R.string.error_copy_order)
	    		       .setTitle(R.string.error)
	    		       .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) { }
						});
	    		AlertDialog dialog = builder.create();
	    		dialog.show();
			}
			progress.setVisibility(View.INVISIBLE);
			add.setVisibility(View.VISIBLE);
		}
	}
	
	private class ItemTask extends AsyncTask<Void, Void, Boolean> {
		@Override
		protected Boolean doInBackground(Void... params) {
			try {
				String phone = preferences.getString("phone", "");
				InputStream in = Server.post(Server.BASKET, Server.getBasketXml(phone, app.getShop().getIdx(), basketId));
				XmlPullParser parser = Server.toXmlParser(in);
				items = XmlParser.getBasket(parser);
			} catch (IOException e) {
				Log.e("Shop", "IOException: " + e.getMessage());
				return false;
			} catch (XmlPullParserException e) {
				Log.e("Shop", "XmlPullParserException: " + e.getMessage());
				return false;
			} catch (NullPointerException e) {
    			Log.e("Shop", "NullPointerException: " + e.getMessage());
				return false;
			} catch (IllegalArgumentException e) {
    			Log.e("Shop", "IllegalArgumentException: " + e.getMessage());
    			return false;
    		}
			return true;
		}
		
		@Override
	    protected void onPostExecute(Boolean success) {
			swipe.setRefreshing(false);
			if (success) {
				checked = new boolean[items.size()];
				for (int i = 0; i < checked.length; i++)
					checked[i] = true;
				
				for (int i = 0; i < items.size(); i++)
	    			if (items.get(i).isShowPicture())
	    				app.downloadImage(items.get(i).getPicture(), callback, context);
					
				ItemArrayAdapter adapter = new ItemArrayAdapter(context, items);
				list.setAdapter(adapter);
				list.setVisibility(View.VISIBLE);
			} else {
				AlertDialog.Builder builder = new AlertDialog.Builder(context);
	    		builder.setMessage(R.string.error_items)
	    		       .setTitle(R.string.error)
	    		       .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								swipe.setRefreshing(true);
								iTask = new ItemTask();
								iTask.execute();
							}
						})
						.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								finish();
							}
						});
	    		AlertDialog dialog = builder.create();
	    		dialog.show();
			}
		}
	}
}